/**
 * Copyright (C) 2013 DaiKit.com - daikit4gxt module (admin@daikit.com)
 *
 *         Project home : http://code.daikit.com/daikit4gxt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// $Id$
package com.daikit.daikit4gxt.client.ui.comparator;

import java.util.Comparator;


/**
 * @author tcaselli
 * @version $Revision$ Last modifier: $Author$ Last commit: $Date$
 * @param <TYPE>
 */
public abstract class DkNullSafeComparator<TYPE> implements Comparator<TYPE>
{

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	@Override
	public int compare(final TYPE o1, final TYPE o2)
	{
		int ret;
		if (o1 == null)
		{
			if (o2 == null)
			{
				ret = 0;
			}
			else
			{
				ret = -1;
			}
		}
		else if (o2 == null)
		{
			ret = 1;
		}
		else
		{
			final String o1ToString = toString(o1);
			final String o2ToString = toString(o2);
			ret = o1ToString == null ? o2ToString == null ? 0 : -1 : o1ToString.compareTo(o2ToString);
		}
		return ret;
	}

	protected abstract String toString(TYPE value);

}
